package org.sam.swing;

import java.awt.BorderLayout;
import java.io.File;
import java.io.FilenameFilter;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileFilter;

import org.sam.swing.model.ImageListModel;
import org.sam.swing.renderer.ImageListCellRender;

/**
 * 图片列表panel对象
 * 
 * @author sam
 *
 */
public class JPanelImageList extends JPanel {

	private static final long serialVersionUID = -7137812466603112529L;

	/**
	 * 图片列表panel对象
	 */
	public JPanelImageList() {
		initCompents();
	}
	
	/**
	 * 初始化控件显示
	 */
	private void initCompents(){
		this.setLayout(new BorderLayout());
		ImageListModel model = new ImageListModel();
		JList<File> list = new JList<>();
		list.setCellRenderer(new ImageListCellRender());
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		this.add(new JScrollPane(list), BorderLayout.CENTER);
		
		JButton btn = new JButton("选择文件....");
		this.add(btn,BorderLayout.NORTH);
		
		btn.addActionListener( (e) -> {
			JFileChooser chooser = new JFileChooser();
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			chooser.setFileFilter(new FileFilter() {
				
				@Override
				public String getDescription() {
					return "png Images";
				}
				
				@Override
				public boolean accept(File f) {
					return f.isDirectory();
				}
			});
			int iResult = chooser.showOpenDialog(this);
			if (iResult != JFileChooser.APPROVE_OPTION)
				return;
			
			File folder = chooser.getSelectedFile();
			File[] files = folder.listFiles(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String name) {
					return name.toLowerCase().endsWith(".png");
				}
			});
			
			model.clearElement();
			for (File f : files){
				model.addElement(f);
			}
			list.setModel(model);
			list.repaint();
		});
	}
}
